/**
 * Created by Administrator on 2015/11/24.
 */

var IUserService = require('../api/service').IUserService
var utils = require('utility')
var path = require('path')
var fs = require('fs')
var parse = require('co-busboy')
var helper = require('./helper')
var User = require('../domain/domain').User
var Recipe = require('../domain/domain').Recipe
var Message = require('../domain/domain').Message
var Page = require('../domain/domain').Page
var Menu = require('../domain/domain').Menu

module.exports = function (app) {

    /**
     * ========预拦截，对具有:nick的url拦截========
     * @type {Router|*|Layer}
     */
    var promise = app.param('nick', function *(nick, next) {
        var user = yield this.db('SELECT * FROM User WHERE nick=?', nick).unique()
        if (!user) {
            this.status = 404
            return
        }
        this.request.user = user

        if(this.session.user && this.session.user.id==this.request.user.id && this.session.user.msgCount != 'undefined'){
            this.session.user.msgCount = yield this.db('SELECT COUNT(*) FROM Message WHERE another_id=? AND another_already_read=0', this.session.user.id).count()
        }

        yield next;
    })

    /**
     * ========用户主页，显示我的菜谱========
     */
    promise.get("/user/:nick", function *() {
        var $self = this
        var nick = $self.params.nick
        var pageNum = $self.query.pageNum || 1
        var recipes = yield $self.db('SELECT * FROM Recipe WHERE owner_id=? LIMIT ?,?', [$self.request.user.id, (pageNum-1)*16, 16]).list()
        var count = yield $self.db('SELECT COUNT(*) FROM Recipe WHERE owner_id=?', $self.request.user.id).count()
        var page = new Page(pageNum, 16, count, recipes)
        yield $self._render("user/recipe", {
            title: nick + "的主页",
            page: page,
            dateformat: utils.YYYYMMDD
        })
    })

    /**
     * ========用户主页，显示我的菜单========
     */
    promise.get("/user/:nick/menu", function *() {
        var $self = this
        var nick = $self.params.nick
        var sqls = []
        sqls.push('SELECT M.id, M.name, M.upvote, M.createOn, M.comment, R.finishedProductImage')
        sqls.push('FROM (SELECT * FROM Menu WHERE user_id=?) M')
        sqls.push('LEFT JOIN Recipe_Menu RM ON RM.m_id=M.id')
        sqls.push('LEFT JOIN Recipe R ON RM.r_id=R.id')
        sqls.push('GROUP BY M.id')
        var menus = yield $self.db(sqls.join(' '), $self.request.user.id).list()
        yield $self._render("user/menu", {
            title: nick + "的主页",
            menus: menus,
            dateformat: utils.YYYYMMDD
        })
    })

    /**
     * ========用户登录=========
     */
    app.post('/login', function *() {
        var $self = this
        var body = $self.request.body
        if(!body.username || !body.password){
            $self.status = 404
            return
        }
        var user = yield $self.db('SELECT * FROM User WHERE username=? AND password=?', [body.username, utils.md5(body.password, "base64")]).unique()
        if(!user){
            yield $self._render('login', {
                title:"登录",
                username: body.username,
                error: "帐号或密码错误"
            })
            return
        }
        console.log('login user is ', JSON.stringify(user))
        var u = new User(user)
        $self.session.user = u
        $self.response.redirect('/')
    })

    app.get('/logout', function *() {
        var $self = this
        delete $self.session.user
        $self.response.redirect('/')
    })

    /**
     * ==========注册===========
     */
    app.post('/signin', function *() {
        var $self = this
        var body = $self.request.body
        var user = new User(body)
        if(!user.username || !user.password || !user.nick){
            yield $self.render('register', {
                title: "注册",
                error: "信息填写不完整"
            })
            return
        }
        user.password = utils.md5(user.password, "base64")
        user = helper.remain(user, 'username', 'password', 'nick', 'createOn', 'portrait')
        yield $self.db('INSERT INTO User SET ?', user).execute()
        $self.response.redirect('/login')
    })

    /**
     * =========设置个人资料页面==========
     */
    promise.get('/user/private/:nick/update/info', function *() {
        var $self = this
        var user = $self.session.user
        user = yield $self.db('SELECT * FROM User WHERE id=?', user.id).unique()
        user.birthday = utils.YYYYMMDD(user.birthday);
        $self.session.user = user
        yield $self._render("user/update_info", {
            title: '设置用户个人资料'
        })
    })

    /**
     * =========设置个人资料==========
     */
    promise.post('/user/private/:nick/update/info', function *() {
        var $self = this
        var body = $self.request.body
        var user = new User(body)
        user = helper.remain(user, "nick", "gender", "telephone", "qq", "birthday", "address")
        if(!user.nick){
            yield $self._render('/user/update_info', {
                error: "昵称不能为空"
            })
        }
        yield $self.db('UPDATE User SET ? WHERE id=?', [user, $self.session.user.id]).execute()
        $self.response.redirect('/user/private/'+$self.session.user.nick+'/update/info')
    })

    /**
     * =========更新头像页面==========
     */
    promise.get('/user/private/:nick/update/portrait', function *() {
        yield this._render('user/update_portrait', {
            title: '更改头像'
        })
    })

    /**
     * =========更新头像处理==========
     */
    promise.post('/user/private/:nick/update/portrait', function *() {
        var $self = this
        var file = $self.request.body.files.portrait
        yield $self.db('UPDATE User SET portrait=? WHERE id=?', [file.url$path, $self.session.user.id]).execute()
        $self.session.user.portrait = file.url$path
        $self.response.redirect('/user/private/'+$self.session.user.nick+'/update/portrait')
    })

    /**
     * =========更新密码页面==========
     */
    promise.get('/user/private/:nick/update/password', function *() {
        yield this._render('user/update_password', {
            title: '更新密码'
        })
    })

    /**
     * =========更新密码==========
     */
    promise.post('/user/private/:nick/update/password', function *() {
        var $self = this
        var old_pwd = $self.request.body.old_pwd
        var new_pwd = $self.request.body.new_pwd
        var user = yield $self.db('SELECT * FROM User WHERE id=? AND password=?', [$self.session.user.id, utils.md5(old_pwd, 'base64')]).unique()
        if(!user){
            yield $self._render('user/update_password', {
                title: '更新密码',
                error_message: '密码错误'
            })
            return
        }
        yield $self.db('UPDATE User SET password=? WHERE id=?', [utils.md5(new_pwd, 'base64'), $self.session.user.id]).execute()
        yield $self._render('user/update_password', {
            title: '更新密码',
            message: '更新成功'
        })
    })

    /**
     * =========发布菜谱页面页面==========
     */
    promise.get('/user/private/:nick/recipe/publish', function *() {
        var $self = this
        var categories = yield $self.db('SELECT id,name FROM RecipeCtg WHERE parent_id IS NULL').list()
        yield (function *(collects) {
            var callee = arguments.callee
            for(var i=0; i<collects.length; i++){
                var array = yield $self.db('SELECT id,name FROM RecipeCtg WHERE parent_id=?', collects[i].id).list()
                if(array.length > 0){
                    yield callee(array)
                    collects[i].children = array
                }
            }
        })(categories)
        var levels = yield $self.db('SELECT * FROM CookieLevel').list()
        var diffs = yield $self.db('SELECT * FROM CookieDiff').list()
        var spends = yield $self.db('SELECT * FROM CookieSpend').list()
        var craftworks = yield $self.db('SELECT * FROM Craftwork').list()
        var flavours = yield $self.db('SELECT * FROM Flavour').list()
        yield $self._render('recipe/publish', {
            title: '发布菜谱',
            categories: categories,
            levels: levels,
            diffs: diffs,
            spends: spends,
            craftworks: craftworks,
            flavours: flavours
        })
    })

    /**
     * =========发布菜谱==========
     */
    promise.post('/user/private/:nick/recipe/publish', function *() {
        var $self = this
        var i
        var filefields = $self.request.body.files
        var recipe = $self.request.body.fields

        recipe.finishedProductImage = filefields.finishedProductImage.url$path
        recipe.step_img = []

        if(Array.isArray(filefields.step_img)){
            filefields.step_img.forEach(function (item) {
                recipe.step_img.push(item.url$path)
            })
        }else{
            recipe.step_img.push(filefields.step_img && filefields.step_img.url$path || null)
        }

        if(Array.isArray(recipe.ingredient)){
            var ingredient = {}
            for(i=0; i<recipe.ingredient.length; i++){
                if(helper.trimspace(recipe.ingredient[i])){
                    ingredient[recipe.ingredient[i]] = recipe.ing[i]
                }
            }
            recipe.ingredient = ingredient
        }
        if(Array.isArray(recipe.seasoning)){
            var seasoning = {}
            for(i=0; i<recipe.seasoning.length; i++){
                if(helper.trimspace(recipe.seasoning[i])){
                    seasoning[recipe.seasoning[i]] = recipe.sea[i]
                }
            }
            recipe.seasoning = seasoning
        }
        if(Array.isArray(recipe.step)){
            var step = []
            for(i=0; i<recipe.step.length; i++){
                if(helper.trimspace(recipe.step[i])){
                    step.push({index: i+1, content: recipe.step[i], image: recipe.step_img[i] || null})
                }
            }
            recipe.step = step
        }
        recipe = new Recipe(recipe)
        recipe.owner_id = $self.session.user.id
        delete recipe.id
        yield $self.db('INSERT INTO Recipe SET ?', recipe).execute()
        yield $self.db('UPDATE User SET recipeCount = recipeCount +1 WHERE id=?', $self.session.user.id).execute()
        $self.response.redirect('/user/'+$self.session.user.nick)
    })

    /**
     * =========用户添加菜单页面=======
     */
    promise.get('/user/private/:nick/menu/publish',function *(){
        yield this._render('/menu/addMenu', {
            title: '添加菜单'
        })
    })

    /**
     * ==========添加菜单=========
     */
    promise.post("/user/private/:nick/menu/publish",function *(){
        var $self = this
        var body = $self.request.body
        var menuName = body.menuName
        var menuDescription = body.menuDescription
        var user = $self.session.user
        var menu = new Menu()
        menu.user_id = user.id
        menu.name = menuName
        menu.description = menuDescription
        menu.createOn =utils.YYYYMMDDHHmmss(new Date().toLocaleString())
        menu = helper.remain(menu,'name','description','user_id','createOn')
        yield $self.database('INSERT INTO Menu SET ?',menu)
        yield $self.db('UPDATE User SET menuCount = menuCount + 1 WHERE id = ?',$self.session.user.id).execute()
        $self.response.redirect('/user/'+$self.session.user.nick+'/menu')
    })

    /**
     * ==========我的收藏，收藏的菜谱===========
     */
    promise.get('/user/:nick/collect/recipe', function *() {
        var $self = this
        var sqls = []
        sqls.push('SELECT R.id,R.title,R.finishedProductImage AS image,R.upvote,R.comment,R.createOn')
        sqls.push('FROM RecipeCollect RC, Recipe R')
        sqls.push('WHERE RC.uid=? AND RC.rid=R.id')
        var recipes = yield $self.db(sqls.join(' '), $self.request.user.id).list()
        yield $self._render('user/collect', {
            title: $self.params.nick,
            collects: recipes,
            isRecipe: true,
            dateformat: utils.YYYYMMDD
        })
    })

    /**
     * ==========我的收藏，收藏的菜单===========
     */
    promise.get('/user/:nick/collect/menu', function *() {
        var $self = this
        var sqls = []
        sqls.push('SELECT M.id, M.name AS title, M.upvote, M.createOn, M.comment, R.finishedProductImage AS image')
        sqls.push('FROM (SELECT ME.* FROM Menu ME,Menu_Collecting MC WHERE MC.u_id=? AND MC.m_id=ME.id) M')
        sqls.push('LEFT JOIN Recipe_Menu RM ON RM.m_id=M.id')
        sqls.push('LEFT JOIN Recipe R ON RM.r_id=R.id')
        sqls.push('GROUP BY M.id')
        var recipes = yield $self.db(sqls.join(' '), $self.request.user.id).list()
        yield $self._render('user/collect', {
            title: $self.params.nick,
            collects: recipes,
            isRecipe: false,
            dateformat: utils.YYYYMMDD
        })
    })

    /**
     * ============关注好友==============
     */
    promise.post('/user/private/:nick/consider', function *() {
        var $self = this
        var table = {
            u_id: $self.session.user.id,
            o_id: $self.request.user.id,
            createOn: new Date()
        }
        try{
            yield $self.db('INSERT INTO Follow SET ?', table).execute()
        }catch(err){
            console.log(err.track)
            $self.body = {
                code: 403,
                message: '你已经关注过啦'
            }
            return
        }
        var message = new Message()
        message.user_id = table.u_id
        message.another_id = table.o_id
        message.obj_id = null
        message.type = Message.TYPE_FOCUS_YOU
        message.another_already_read = false
        delete message.id
        yield $self.db('INSERT INTO Message SET ?', message).execute()
        yield $self.db('UPDATE User SET focusCount=focusCount+1 WHERE id=?', table.u_id).execute()
        yield $self.db('UPDATE User SET fansCount=fansCount+1 WHERE id=?', table.o_id).execute()
        $self.body = {
            code: 200,
            message: '已关注'
        }
    })

    /**
     * =========获取该用户下的所有菜单==========
     */
    promise.get('/user/private/:nick/menu/list', function *() {
        var $self = this
        var menus = yield $self.db('SELECT id, name FROM Menu WHERE user_id=?', this.session.user.id).list()
        $self.body = {
            code: 200,
            menus: menus
        }
    })

    /**
     * ==========添加菜谱到菜单===========
     */
    promise.post('/user/private/:nick/menu/add/recipe', function *() {
        var $self = this
        var mid = $self.request.body.mid
        var rid = $self.request.body.rid
        var obj = {
            m_id: mid,
            r_id: rid
        }
        try{
            yield $self.db('INSERT INTO Recipe_Menu SET ?', obj).execute()
            yield $self.db('UPDATE Menu SET recipeCount = recipeCount + 1 WHERE id = ?',mid).execute()
        }catch(err){
            console.log(err.track)
            $self.body = {
                code: 403,
                message: '已在该菜单中'
            }
            return
        }
        $self.body = {
            code: 200,
            message: '添加成功'
        }
    })

    /**
     * ==========我的粉丝页面===========
     */
    promise.get('/user/:nick/fans', function *() {
        var $self = this
        var sqls = [
            "SELECT U.id, U.nick, U.portrait, U.createOn, U.recipeCount AS 'count.recipe', U.menuCount AS 'count.menu', U.focusCount AS 'count.focus', U.fansCount AS 'count.fans' ",
            "FROM Follow F, User U",
            "WHERE o_id=? AND u_id=U.id"
        ]
        var fans = yield $self.db(sqls.join(' '), $self.request.user.id).list()
        for(var i=0; i<fans.length; i++){
            fans[i] = helper.params2obj(fans[i])
        }
        yield $self._render('user/fans', {
            title: '粉丝',
            fans: fans
        })
    })

    /**
     * ==========我的关注==========
     */
    promise.get('/user/:nick/consider', function *() {
        var $self = this
        var sqls = [
            "SELECT U.id, U.nick, U.portrait, U.createOn, U.recipeCount AS 'count.recipe', U.menuCount AS 'count.menu', U.focusCount AS 'count.focus', U.fansCount AS 'count.fans' ",
            "FROM Follow F, User U",
            "WHERE u_id=? AND o_id=U.id"
        ]
        var considers = yield $self.db(sqls.join(' '), $self.request.user.id).list()
        for(var i=0; i<considers.length; i++){
            considers[i] = helper.params2obj(considers[i])
        }
        yield $self._render('user/considers', {
            title: '粉丝',
            considers: considers
        })
    })

    /**
     * ==========我的消息===========
     */
    promise.get('/user/private/:nick/message', function *() {
        var $self = this
        var messages = yield $self.db('SELECT M.*, U.nick AS user_nick FROM Message M, User U WHERE M.another_id=? AND U.id=M.user_id ORDER BY M.createOn DESC', $self.session.user.id).list()
        for(var i in messages){
            switch(messages[i].type){
                case Message.TYPE_UPVOTE_MENU:
                    var obj = yield $self.db('SELECT name FROM Menu WHERE id=?', messages[i].obj_id).unique()
                    messages[i].obj_title = obj && obj.name || null
                    break
                case Message.TYPE_UPVOTE_RECIPE:
                    var obj = yield $self.db('SELECT title FROM Recipe WHERE id=?', messages[i].obj_id).unique()
                    messages[i].obj_title = obj && obj.title || null
                    break
            }
        }
        yield $self.db('UPDATE Message SET another_already_read=1 WHERE another_id=?', $self.session.user.id).execute()
        yield $self._render('user/message', {
            title: '我的消息',
            messages: messages,
            Message: Message,
            dateformat: utils.YYYYMMDD
        })
    })



}